package com.draven.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.draven.mall.common.ApiResponse;
import com.draven.mall.entity.Order;
import com.draven.mall.entity.User;
import com.draven.mall.service.OrderService;
import com.draven.mall.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private OrderService orderService;

    /**
     * 获取用户订单历史
     */
    @GetMapping("/orders/{userId}")
    public ApiResponse getUserOrders(
            @PathVariable Long userId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size) {
        // 验证用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        
        // 创建分页对象
        Page<Order> pageParam = new Page<>(page, size);
        
        // 查询条件：用户ID
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId)
                   .orderByDesc(Order::getCreatedTime);
        
        // 查询订单
        IPage<Order> pageResult = orderService.page(pageParam, queryWrapper);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        return ApiResponse.success(result);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/{id}")
    public ApiResponse getUserInfo(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user != null) {
            // 处理敏感信息
            user.setPassword(null);
            return ApiResponse.success(user);
        } else {
            return ApiResponse.error("用户不存在");
        }
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ApiResponse login(@RequestParam String username, @RequestParam String password) {
        User user = userService.login(username, password);
        if (user != null) {
            return ApiResponse.success(user);
        }
        return ApiResponse.error("用户名或密码错误");
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ApiResponse register(@RequestBody User user) {
        User registeredUser = userService.register(user);
        if (registeredUser != null) {
            return ApiResponse.success(registeredUser);
        }
        return ApiResponse.error("注册失败，用户名或手机号已存在");
    }

    @PutMapping
    @ApiOperation("更新用户信息")
    public ApiResponse update(@RequestBody User user) {
        if (user.getId() == null) {
            return ApiResponse.error("用户ID不能为空");
        }
        user.setPassword(null); // 不允许通过此接口修改密码
        boolean success = userService.updateById(user);
        return success ? ApiResponse.success() : ApiResponse.error("更新失败");
    }
}
